package bosc.cn.tunnel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author tianshq
 * @date 2025/9/8 23:23
 * @description TunnelWebSocketHandler
 * WebSocket 消息处理器
 */
@Slf4j
public class TunnelWebSocketHandler extends TextWebSocketHandler {
    private final SignServiceTunnelClient tunnelClient;

    public TunnelWebSocketHandler(SignServiceTunnelClient tunnelClient) {
        this.tunnelClient = tunnelClient;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("WebSocket connection established");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("Received message: {}", payload);

        // 解析响应，提取 requestId
        String requestId = extractRequestId(payload);
        if (requestId != null) {
            tunnelClient.setResponse(payload, requestId);
        } else {
            log.error("requestId is null");
        }
    }

    // 从响应中提取 requestId
    private String extractRequestId(String response) {
        // 根据实际的响应格式解析 requestId
        // 假设响应格式为: requestId@!@JSON

        String[] parts = response.split(SignServiceTunnelClient.REGEX);
        if (parts.length >= 1) {
            return parts[0];
        }
        return null;
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("WebSocket transport error", exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("WebSocket connection closed: {}", status);
    }
}

